<template>
  <Form :model="formState" ref="formRef" name="BasicForm">
    <div class="md:flex">
      <div class="md: w-1/2">
        <FormItem name="rate" label="单位请求数" :rules="[{ required: true, message: '请输入单位请求数' }]">
          <Input v-model:value="formState.rate" />
        </FormItem>
      </div>
      <div class="md:mx-5">/</div>
      <div class="md: w-1/3">
        <FormItem name="limitRefreshPeriod" label="" :rules="[{ required: true, message: '请输入值' }]">
          <Input v-model:value="formState.limitRefreshPeriod" />
        </FormItem>
      </div>
      <div class="md:mx-5"></div>
      <div class="md: w-1/6">
        <FormItem name="rlTimeUnit" label="" :rules="[{ required: true, message: '请选择单位' }]">
          <Select v-model:value="formState.rlTimeUnit">
            <SelectOption v-for="unit in unitList" v-bind:key="unit.value" :value="unit.value">{{ unit.label }}</SelectOption>
          </Select>
        </FormItem>
      </div>
    </div>
  </Form>
</template>

<script lang="ts" setup>
import { Form, FormItem, Select, Input, SelectOption } from 'ant-design-vue';
import { onMounted, reactive, ref, toRaw } from 'vue';
import { ValidateErrorEntity } from 'ant-design-vue/es/form/interface';

interface FormState {
  rate: string;
  limitRefreshPeriod: string;
  rlTimeUnit: string;
}

let formState = reactive<Record<string, any>>({});
const formRef = ref();
const emit = defineEmits(['submit', 'change', 'success', 'error']);
const isEdit = ref(false);
const unitList = ref([
  {
    label: 'ms',
    value: 'Ms',
  },
  {
    label: 's',
    value: 'S',
  },
]);

onMounted(() => {
  formState.rlTimeUnit = 'Ms';
});

function setData(fieldValue: any) {
  formState.rate = fieldValue.rate;
  formState.limitRefreshPeriod = fieldValue.limitRefreshPeriod;
  formState.rlTimeUnit = fieldValue.rlTimeUnit;
  isEdit.value = true;
}

function submitHandler() {
  formRef.value
    .validate()
    .then(() => {
      let params = toRaw(formState);
      emit('submit', params);
      emit('success');
      isEdit.value = false;
      formState = undefined;
    })
    .catch((error: ValidateErrorEntity<FormState>) => {
      emit('error', error);
    });
}

defineExpose({ submitHandler, setData });
</script>
